package dycloud.mabaoguo.User.controller;


import java.util.stream.Collectors;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import org.bson.Document;
import dycloud.mabaoguo.User.model.roleCambat.HistoryRoleCombat;
import dycloud.mabaoguo.User.model.Json_Atk_Combat;
import dycloud.mabaoguo.User.model.Json_Def_Combat;
import dycloud.mabaoguo.User.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.ArrayList;
@Slf4j
@Service
public class CombatRankScheduler {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private MongoTemplate mongoTemplate;

    // 每周五晚上24:00执行
    //@Scheduled(cron = "0 0/5 * * * ?")  //Test 五分钟 一次
    @Scheduled(cron = "0 0 0 ? * SAT") //每周六 午夜 00
    public void updateCombatRanks() {
        try {
            log.info("35: Role Combat Table Update.");
            // 步骤 1: 执行双阵营战力排序
            //更新双阵营 战力排行
            userInfoService.updateAtkCombatRank();
            userInfoService.updateDefCombatRank();

            // 步骤 2: 获取当前日期
            String currentDate = LocalDate.now().toString();  // "2024-12-01"

            // 步骤 3: 创建新的历史表并插入数据
            createAndInsertToHistoryTable(Json_Atk_Combat.class, currentDate);
            createAndInsertToHistoryTable(Json_Def_Combat.class, currentDate);

            // 步骤 5: 清空基础表
            clearCurrentWeekTables();

            log.info("Combat rank update and history tables created successfully for date: {}", currentDate);
        } catch (Exception e) {
            log.error("Error during scheduled combat rank update: {}", e.getMessage(), e);
        }
    }
    // 创建并插入到历史表的方法
    private void createAndInsertToHistoryTable(Class<?> combatClass, String currentDate) {
        try {

            // 获取表的数据
            List<?> data = mongoTemplate.findAll(combatClass);
            // 如果没有数据，跳过插入
            if (data.isEmpty()) {
                log.warn("No data found for combat class: {}. Skipping insertion.", combatClass.getSimpleName());
                return;
            }

            // 构造新表名
            String newTableName = combatClass.getSimpleName() + "_" + currentDate;

            // 将数据转换为 Document 类型的列表
            List<Document> documents = data.stream()
                    .map(this::convertToDocument)  // 转换为 Document
                    .collect(Collectors.toList());

            // 将数据插入到新的历史表
            mongoTemplate.getCollection(newTableName).insertMany(documents);

            log.info("Created and inserted data into table: {}", newTableName);


            // 获取 HistoryRoleCombat 对象并更新表名列表
            HistoryRoleCombat historyRecord = mongoTemplate.findOne(new Query(), HistoryRoleCombat.class);

            // 如果没有记录，创建一个新的记录
            if (historyRecord == null) {
                historyRecord = new HistoryRoleCombat();
                historyRecord.setAtkTableNames(new ArrayList<>());
                historyRecord.setDefTableNames(new ArrayList<>());
            }

            // 根据 combatClass 来决定更新哪个列表
            if (combatClass.equals(Json_Atk_Combat.class)) {
                // 如果历史记录中已经存在这个表名，替换为最新的
                historyRecord.getAtkTableNames().add(newTableName); // 或者替换最新的
            } else if (combatClass.equals(Json_Def_Combat.class)) {
                historyRecord.getDefTableNames().add(newTableName); // 或者替换最新的
            }

            // 保存更新后的 HistoryRoleCombat 记录
            mongoTemplate.save(historyRecord);


        } catch (Exception e) {
            log.error("Error creating and inserting to history table: {}", e.getMessage(), e);
        }
    }
    private void clearCurrentWeekTables() {
        try {
            // 清空基础表（用于下周的开始）
            mongoTemplate.dropCollection(Json_Atk_Combat.class);
            mongoTemplate.dropCollection(Json_Def_Combat.class);

            log.info("Cleared current week's combat rank tables.");
        } catch (Exception e) {
            log.error("Error clearing current week's tables: {}", e.getMessage(), e);
        }
    }

    /**
     * 将对象转换为 Document
     *
     * @param object 要转换的对象
     * @return 转换后的 Document 对象
     */
    private Document convertToDocument(Object object) {
        Document doc = new Document();

        // 根据对象类型（例如 Json_Atk_Combat 或 Json_Def_Combat）提取字段并填充到 Document 中
        if (object instanceof Json_Atk_Combat) {
            Json_Atk_Combat atkCombat = (Json_Atk_Combat) object;
            doc.append("playid", atkCombat.getPlayid());
            doc.append("combat", atkCombat.getCombat());
            doc.append("roleRank", atkCombat.getRoleRank());
        } else if (object instanceof Json_Def_Combat) {
            Json_Def_Combat defCombat = (Json_Def_Combat) object;
            doc.append("playid", defCombat.getPlayid());
            doc.append("combat", defCombat.getCombat());
            doc.append("roleRank", defCombat.getRoleRank());
        }

        return doc;
    }
}
